<template>
  <div class="map-container">
    <div id="container" style="width: 100%; height: 100%"></div>
  </div>
</template>
  
<script setup>
import { onMounted, ref, nextTick } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { bus } from "@/utils/mitt";

const customCenter = ref([]); // 初始化为空数组
const adddress = ref(""); // 初始化为空字符串

// 地图实例
let map = null;

// 更新地图中心点和标记的函数
const updateMap = () => {
  if (customCenter.value.length === 2) {
    map.setCenter(customCenter.value); // 设置地图中心点
    new AMap.Marker({
      position: customCenter.value,
      map: map,
      title: adddress.value || "未知地址", // 防止标题为空
    });
  }
};

onMounted(() => {
  bus.on("latitudeAndLongitude", (data) => {
    customCenter.value = [parseFloat(data[0]), parseFloat(data[1])];
    updateMap(); // 更新地图
  });

  bus.on("companyAddress", (data) => {
    adddress.value = data;
    updateMap(); // 更新地图
  });

  AMapLoader.load({
    key: "a2abef748cc970c62aad550bdb7ad008",
    securityJsCode: "9119011b9d67900449841e62839ef065",
    version: "2.0",
    plugins: [
      "AMap.Geolocation",
      "AMap.PlaceSearch",
      "AMap.AutoComplete",
      "AMap.Geocoder",
    ],
  })
    .then((AMap) => {
      nextTick(() => { // 确保 DOM 更新完成
      map = new AMap.Map("container", {
        viewMode: "2D",
        zoom: 15,
        center: [116.397428, 39.90923], // 默认中心点
      });
      updateMap(); // 初始化时更新地图
    });
    })
    .catch((e) => {
      console.error("地图加载失败", e);
    });
});
</script>
  
  <style scoped>
.map-container {
  width: 100%;
  height: 100%;
}
#search_input {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 200px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
</style>